<template>
  <div>
    <!--条件筛选-->
    <TopFilter ref="topFilter" :list="topFilterList" :cols="3" labelWidth="120" :collapse="false" @filterChange="changeHandle" @onCollapse="collapseHandle"></TopFilter>
    <!-- 列筛选-->
    <FilterTable
      ref="table"
      columnsRef="lhmHoursStatistics"
      :columns="columns"
      :dataSource="dataSource"
      :isExportExcel="isExportExcel"
      exportFileName="工时统计.xlsx"
      :isSelectColumn="false"
      :isMemoryPagination="true"
      :onColumnsChange="columns => (this.columns = columns)"
    >
      <!--列操作-->
      <template slot="controls">
        <el-button type="primary" @click="handleCheckDetail">查看明细</el-button>
        <el-button size="small" type="primary" @click="openHandle">工时统计汇总</el-button>
      </template>
    </FilterTable>
    <Drawer title="工时统计汇总" :visible.sync="isShowSummary" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <Summary :formData="formData" @close="isShowSummary = false" />
    </Drawer>
    <BaseDialog title="工时统计明细" :visible.sync="detailVisible" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <queryDetail :fetchParams="filterParams" :isExportExcel="isExportExcel" @close="detailVisible = false" />
    </BaseDialog>
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import moment from 'moment';
import { getHoursStatistics, queryWorkGroup } from '@/api/repair/queryStatistics/queryAccounts';
import { getModel } from '@/api/customerRepair/customerCare/insuranceDueRemind/index';
import { searchRoleByCode, searchRoleByCodes } from '@/api/common/empSelect/index';
import dictCode from '@/utils/dictCode';
import { arrayObjDeWeight } from '@/utils/index'; // 去重
import { getUserListSelect } from '@/api/report/repair/repairreport';
// 维修类别
import { getfindAllRepairType } from '@/api/repair/business/customer/history';
// 获取员工
import { getDealerUser } from '@/api/customerRepair/customerComplaint/customerComplaintReception';
import Summary from './summary';
import queryDetail from './queryDetail';
import { menuUserAction } from '@/api/repair/repairReception/repairBusinessManger';

export default {
  name: 'LHMHoursStatistics',
  components: {
    Summary,
    queryDetail
  },
  mixins: [dictionary],
  data() {
    return {
      topFilterList: this.createTopFilterList(),
      dataSource: [],
      columns: this.createTableColumns(),
      isShowSummary: false,
      formData: {},
      selectedRows: [], // 选中的table列表
      detailVisible: false, // 是否显示详情table
      filterParams: {}, // 查询参数
      isExportExcel: false // 是否显示前端excel导出按钮
    };
  },
  mounted() {
    // 分页
    this.BaseTable = this.$refs.table.$refs.pageTable;
    this.init();
    this.getDealerUser();
    this.getZdjsSelect();
    this.getfindAllRepairType();
    this.queryWorkGroup();
    this.menuUserAction();
  },
  methods: {
    createTopFilterList() {
      return [
        {
          type: 'RANGE_DATE',
          fieldName: 'inOutTimeStr|inOutTimeEnd',
          initialValue: [
            moment()
              .startOf('month')
              .format('YYYY-MM-DD HH:mm:ss'),
            moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
          ],
          labelOptions: {
            fieldName: 'inOutTime',
            initialValue: 'inTime',
            itemList: [
              { text: '派工日期', value: 'inTime' },
              { text: '审核日期', value: 'outTime' },
              { text: '结清日期', value: 'inOutTime' },
              { text: '最后结算日期', value: 'inOutTimeOne' },
              { text: '出厂日期', value: 'deliveryDate' }
            ]
          },
          rules: [{ required: true, message: '请选日期范围', trigger: 'change' }]
        },
        // {
        //   type: 'SELECT',
        //   label: '查询方式',
        //   fieldName: 'dateType',
        //   placeholder: '选择日期',
        //   itemList: [
        //     { text: '派工日期', value: 1001 },
        //     { text: '审核日期', value: 1002 },
        //     { text: '出厂日期', value: 1003 },
        //     { text: '结清日期', value: 1004 },
        //     { text: '最后结算日期', value: 1005 }
        //   ]
        // },
        // {
        //   type: 'RANGE_DATE',
        //   label: '日期',
        //   fieldName: 'beginDate|endDate',
        //   placeholder: '选择日期'
        // },
        {
          type: 'MULTIPLE_SELECT',
          label: '班组',
          fieldName: 'workgroupCode',
          placeholder: '请选择...',
          clearable: true,
          filterable: true,
          noResetable: true,
          initialValue: [],
          itemList: []
        },
        {
          type: 'SELECT',
          label: '主修人',
          fieldName: 'technician',
          placeholder: '请选择...',
          clearable: true,
          filterable: true,
          itemList: []
        },
        {
          type: 'SELECT',
          label: '维修类别',
          fieldName: 'repairTypeCode',
          placeholder: '请选择...',
          clearable: true,
          filterable: true,
          itemList: []
        },
        {
          type: 'SELECT',
          label: '车型',
          fieldName: 'model',
          placeholder: '请选择...',
          clearable: true,
          filterable: true,
          itemList: []
        },
        {
          type: 'CHECKBOX',
          label: '工时费统计免费性质',
          fieldName: 'isMoney',
          options: {
            trueValue: '10041001',
            falseValue: ''
          }
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '维修类别',
          dataIndex: 'REPAIR_TYPE_NAME',
          sorter: true,
          filter: true,
          showOverflowTooltip: true,
          filterType: 'input'
        },
        {
          title: '车系',
          dataIndex: 'SERIES_NAME',
          sorter: true,
          filter: true,
          showOverflowTooltip: true,
          filterType: 'input'
        },
        {
          title: '悦•享60分',
          dataIndex: 'isQuickRepair',
          sorter: true,
          showOverflowTooltip: true,
          editable: false,
          editType: 'select',
          editItems: this.createDictList('1004'),
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('1004')
        },
        {
          title: '车型',
          dataIndex: 'MODEL_NAME',
          sorter: true,
          filter: true,
          showOverflowTooltip: true,
          filterType: 'input'
        },
        // {
        //   title: '部门',
        //   dataIndex: 'ORG_NAME',
        //   sorter: true,
        //   filter: true,
        //   showOverflowTooltip: true,
        //   filterType: 'input'
        // },
        {
          title: '班组',
          dataIndex: 'WORKGROUP_NAME',
          sorter: true,
          filter: true,
          showOverflowTooltip: true,
          filterType: 'input'
        },
        {
          title: '主修人',
          dataIndex: 'TECHNICIAN',
          sorter: true,
          showOverflowTooltip: true,
          editable: false,
          editType: 'select',
          editItems: [],
          filter: true,
          filterType: 'checkbox',
          filterItems: []
        },
        {
          title: '维修次数',
          dataIndex: 'counts',
          sorter: true,
          filter: true,
          align: 'center',
          summation: true,
          showOverflowTooltip: true,
          filterType: 'number'
        },
        {
          title: '内部工时',
          dataIndex: 'ASSIGN_LABOUR_HOUR',
          sorter: true,
          filter: true,
          align: 'right',
          precision: 2,
          summation: true,
          showOverflowTooltip: true,
          filterType: 'number'
        },
        {
          title: '工时',
          dataIndex: 'STD_LABOUR_HOUR',
          sorter: true,
          filter: true,
          align: 'right',
          precision: 2,
          summation: true,
          showOverflowTooltip: true,
          filterType: 'number'
        },
        {
          title: '工时费',
          dataIndex: 'LABOUR_AMOUNT',
          sorter: true,
          filter: true,
          align: 'right',
          precision: 2,
          summation: true,
          showOverflowTooltip: true,
          filterType: 'number'
        },
        {
          title: '优惠后工时费',
          dataIndex: 'REAL_AMOUNT',
          sorter: true,
          filter: true,
          align: 'right',
          precision: 2,
          summation: true,
          showOverflowTooltip: true,
          filterType: 'number'
        },
        {
          title: '返工次数',
          dataIndex: 'unCounts',
          sorter: true,
          filter: true,
          align: 'center',
          summation: true,
          showOverflowTooltip: true,
          filterType: 'number'
        },
        {
          title: '返工工时',
          dataIndex: 'UN_STD_LABOUR_HOUR',
          sorter: true,
          filter: true,
          align: 'right',
          precision: 2,
          summation: true,
          showOverflowTooltip: true,
          filterType: 'number'
        },
        {
          title: '返工工时费',
          dataIndex: 'UN_LABOUR_AMOUNT',
          sorter: true,
          filter: true,
          align: 'right',
          precision: 2,
          summation: true,
          showOverflowTooltip: true,
          filterType: 'number'
        },
        // {
        //   title: '返工扣款',
        //   dataIndex: 'BACK_AFTER_DISCOUNT_AMOUNT',
        //   sorter: true,
        //   filter: true,
        //   showOverflowTooltip: true,
        //   filterType: 'input'
        // },
        {
          title: '次数%',
          dataIndex: 'counts2',
          sorter: true,
          filter: true,
          align: 'right',
          showOverflowTooltip: true,
          filterType: 'number'
        },
        {
          title: '工时%',
          dataIndex: 'ASSIGN_LABOUR_HOUR2',
          sorter: true,
          filter: true,
          align: 'right',
          showOverflowTooltip: true,
          filterType: 'number'
        },
        {
          title: '工时费%',
          dataIndex: 'LABOUR_AMOUNT2',
          sorter: true,
          filter: true,
          align: 'right',
          showOverflowTooltip: true,
          filterType: 'number'
        },
        {
          title: '返工次数%',
          dataIndex: 'unCounts2',
          sorter: true,
          filter: true,
          align: 'right',
          showOverflowTooltip: true,
          filterType: 'number'
        },
        {
          title: '返工工时%',
          dataIndex: 'UN_STD_LABOUR_HOUR2',
          sorter: true,
          filter: true,
          align: 'right',
          showOverflowTooltip: true,
          filterType: 'number'
        },
        {
          title: '返工工时费%',
          dataIndex: 'LABOUR_AMOUNT3',
          sorter: true,
          filter: true,
          align: 'right',
          showOverflowTooltip: true,
          filterType: 'number'
        }
        // {
        //   title: '返工扣款%',
        //   dataIndex: 'BACK_AFTER_DISCOUNT_AMOUNT_PERCENT',
        //   sorter: true,
        //   filter: true,
        //   showOverflowTooltip: true,
        //   filterType: 'input'
        // }
      ];
    },
    // 查询导出参数
    async menuUserAction() {
      let res = await menuUserAction();
      for (const item of res.data) {
        if (item.actionUrl == '/repair/queryStatistics/hoursStatistics') {
          this.isExportExcel = true;
        }
      }
    },
    // 维修类型
    async getfindAllRepairType() {
      const res = await getfindAllRepairType();
      let list = res.data.map(x => ({ text: x.REPAIR_TYPE_NAME, value: x.REPAIR_TYPE_CODE + '' }));
      this.topFilterList.find(item => item.fieldName === 'repairTypeCode').itemList = list; // 维修类型
    },
    // 班组
    async queryWorkGroup() {
      const res = await queryWorkGroup();
      let list = res.data.map(x => ({ text: x.WORKGROUP_NAME, value: x.WORKGROUP_CODE }));
      let totalWorkGroupCode = res.data.map(item => item.WORKGROUP_CODE);
      this.topFilterList.find(item => item.fieldName === 'workgroupCode').itemList = list;
      this.topFilterList.find(item => item.fieldName === 'workgroupCode').initialValue = totalWorkGroupCode;
    },
    async init() {
      // 车型
      let carModel = await getModel();
      this.topFilterList.find(item => item.fieldName === 'model').itemList = carModel.data.map(x => ({
        text: x.MODEL_NAME,
        value: x.MODEL_ID + ''
      }));
    },
    async getZdjsSelect() {
      let technician = { role: dictCode.TECHNICIAN }; // 指定技师
      const technicianRes = await searchRoleByCodes(technician);
      this.topFilterList.find(item => item.fieldName === 'technician').itemList = technicianRes.data.map(x => ({
        text: x.employeeName,
        value: x.userId + ''
      }));
    },
    // 获取所有人的信息
    async getDealerUser() {
      const res = await getDealerUser();
      let userData = arrayObjDeWeight(res.data, 'userId');
      this.columns.find(x => x.dataIndex == 'TECHNICIAN').dictItems = this.columns.find(x => x.dataIndex == 'TECHNICIAN').filterItems = this.columns.find(
        x => x.dataIndex == 'TECHNICIAN'
      ).editItems = userData.map(x => ({
        text: x.employeeName,
        value: x.userId + ''
      }));
    },

    async openHandle() {
      let data = await this.$refs.topFilter.GET_FORM_DATA();
      if (data[1].inOutTimeEnd) {
        data[1].inOutTimeStr = data[1].inOutTimeStr.slice(0, 10) + ' 00:00:00';
        data[1].inOutTimeEnd = data[1].inOutTimeEnd.slice(0, 10) + ' 23:59:59';
      }
      this.formData = data[1];
      console.log('formData', this.formData);
      this.isShowSummary = true;
    },
    async changeHandle(val) {
      let filterData = JSON.parse(JSON.stringify(val));
      this.dataSource = [];
      this.BaseTable.START_LOADING();
      // console.log('val', val);
      // this.printList.inOutTimeStr = val.inOutTimeStr;
      // this.printList.inOutTimeEnd = val.inOutTimeEnd;
      if (filterData.inOutTimeEnd) {
        filterData.inOutTimeStr = filterData.inOutTimeStr.slice(0, 10) + ' 00:00:00';
        filterData.inOutTimeEnd = filterData.inOutTimeEnd.slice(0, 10) + ' 23:59:59';
      }
      // filterData.workgroupCode = filterData.workgroupCode ? filterData.workgroupCode.join(',') : '';
      try {
        let res = await getHoursStatistics(Object.assign({}, filterData, { workgroupCode: filterData.workgroupCode ? filterData.workgroupCode.join(',') : '' }));
        if (res.resultCode == 200) {
          this.dataSource = res.data;
        }
      } catch (error) {
      } finally {
        this.BaseTable.STOP_LOADING();
      }
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    // 点击查看详情
    async handleCheckDetail() {
      let formData = await this.$refs.topFilter.GET_FORM_DATA();
      this.filterParams = Object.assign({}, formData[1], {
        workgroupCode: formData[1].workgroupCode ? formData[1].workgroupCode.join(',') : '',
        inOutTimeStr: formData[1].inOutTimeStr ? formData[1].inOutTimeStr.slice(0, 10) + ' 00:00:00' : '',
        inOutTimeEnd: formData[1].inOutTimeEnd ? formData[1].inOutTimeEnd.slice(0, 10) + ' 23:59:59' : ''
      });
      this.detailVisible = true;
    }
  }
};
</script>

<style lang="less" scoped></style>
